<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MOWu台账Excel数据提取（测试版）</title>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3f51b5;
            --primary-dark: #303f9f;
            --primary-light: #c5cae9;
            --accent: #ff4081;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --light: #f5f5f5;
            --dark: #212121;
            --gray: #757575;
            --light-gray: #e0e0e0;
            --bg: #f5f7ff;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: var(--dark);
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            border-radius: 16px;
            box-shadow: 0 12px 50px rgba(0, 0, 0, 0.18);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(120deg, var(--primary), var(--primary-dark));
            color: white;
            padding: 30px 40px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        header::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
            transform: rotate(30deg);
        }
        
        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
            position: relative;
        }
        
        .subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
            max-width: 800px;
            margin: 0 auto;
            font-weight: 300;
            position: relative;
        }
        
        .content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        @media (max-width: 1000px) {
            .content {
                grid-template-columns: 1fr;
            }
        }
        
        .panel {
            background-color: white;
            border-radius: 14px;
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
            padding: 30px;
            transition: all 0.3s ease;
            border: 1px solid var(--light-gray);
            position: relative;
            overflow: hidden;
        }
        
        .panel::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--accent));
        }
        
        .panel-title {
            font-size: 1.5rem;
            color: var(--primary-dark);
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--primary-light);
            display: flex;
            align-items: center;
        }
        
        .panel-title i {
            margin-right: 12px;
            font-size: 1.3em;
            color: var(--primary);
        }
        
        .drop-area {
            border: 3px dashed var(--primary-light);
            border-radius: 12px;
            padding: 50px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background-color: #f8fbff;
            margin-bottom: 25px;
            position: relative;
        }
        
        .drop-area:hover, .drop-area.drag-over {
            border-color: var(--primary);
            background-color: #edf4ff;
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(63, 81, 181, 0.15);
        }
        
        .drop-area i {
            font-size: 64px;
            color: var(--primary);
            margin-bottom: 15px;
            display: block;
            opacity: 0.8;
            transition: all 0.3s;
        }
        
        .drop-area:hover i {
            transform: scale(1.1);
            opacity: 1;
        }
        
        .drop-text {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: var(--dark);
            font-weight: 500;
        }
        
        .drop-hint {
            color: var(--gray);
            font-size: 1rem;
        }
        
        .columns-section {
            margin: 30px 0;
        }
        
        .columns-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .add-column-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .add-column-input {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid var(--primary-light);
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .add-column-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(63, 81, 181, 0.2);
        }
        
        .add-column-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 1rem;
            font-weight: 500;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .add-column-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(63, 81, 181, 0.3);
        }
        
        .columns-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .column-item {
            padding: 16px;
            background: linear-gradient(135deg, #f0f4ff 0%, #e8edff 100%);
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-left: 4px solid var(--primary);
            transition: all 0.3s;
        }
        
        .column-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(63, 81, 181, 0.15);
        }
        
        .column-name {
            font-weight: 500;
            color: var(--dark);
        }
        
        .column-remove {
            color: var(--danger);
            cursor: pointer;
            font-size: 1.2rem;
            transition: all 0.2s;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .column-remove:hover {
            background-color: rgba(244, 67, 54, 0.1);
            transform: scale(1.1);
        }
        
        .btn {
            display: inline-block;
            background: linear-gradient(120deg, var(--primary), var(--primary-dark));
            color: white;
            border: none;
            padding: 16px 32px;
            font-size: 1.1rem;
            font-weight: 600;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
            width: 100%;
            margin-top: 20px;
            box-shadow: 0 6px 15px rgba(63, 81, 181, 0.3);
            letter-spacing: 0.5px;
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(63, 81, 181, 0.4);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .file-list {
            margin-top: 30px;
            max-height: 250px;
            overflow-y: auto;
            border: 1px solid var(--light-gray);
            border-radius: 10px;
            padding: 15px;
            background: #f8fbff;
        }
        
        .file-list-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 0 5px;
        }
        
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid var(--light-gray);
            transition: background 0.2s;
            border-radius: 6px;
        }
        
        .file-item:hover {
            background-color: #edf4ff;
        }
        
        .file-item:last-child {
            border-bottom: none;
        }
        
        .file-name {
            flex-grow: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding-right: 15px;
            font-size: 0.95rem;
        }
        
        .file-size {
            color: var(--gray);
            font-size: 0.85rem;
            min-width: 80px;
            text-align: right;
        }
        
        .file-remove {
            color: var(--danger);
            cursor: pointer;
            margin-left: 15px;
            font-size: 1.2rem;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background 0.2s;
        }
        
        .file-remove:hover {
            background-color: rgba(244, 67, 54, 0.1);
        }
        
        .result-area {
            margin-top: 30px;
        }
        
        .result-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .result-table-container {
            border: 1px solid var(--light-gray);
            border-radius: 10px;
            overflow: hidden;
            max-height: 400px;
            overflow-y: auto;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        
        .result-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.95rem;
        }
        
        .result-table th {
            background-color: var(--primary);
            color: white;
            padding: 14px 16px;
            text-align: left;
            position: sticky;
            top: 0;
            font-weight: 600;
        }
        
        .result-table td {
            padding: 12px 16px;
            border-bottom: 1px solid var(--light-gray);
        }
        
        .result-table tr:nth-child(even) {
            background-color: #f8fbff;
        }
        
        .result-table tr:hover {
            background-color: #e8f0ff;
        }
        
        .status {
            display: flex;
            align-items: center;
            margin-top: 25px;
            padding: 18px;
            border-radius: 10px;
            background-color: #f0f7ff;
            border-left: 4px solid var(--primary);
        }
        
        .status-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            font-size: 1.2rem;
        }
        
        .status-icon.info {
            background-color: var(--primary);
            color: white;
        }
        
        .status-icon.success {
            background-color: var(--success);
            color: white;
        }
        
        .status-icon.error {
            background-color: var(--danger);
            color: white;
        }
        
        .download-btn {
            background: linear-gradient(120deg, var(--success), #2ecc71);
            margin-top: 25px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
        }
        
        .download-btn:hover {
            box-shadow: 0 8px 20px rgba(76, 175, 80, 0.4);
        }
        
        .hidden {
            display: none;
        }
        
        .progress-container {
            height: 10px;
            background-color: var(--light-gray);
            border-radius: 5px;
            margin: 20px 0;
            overflow: hidden;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, var(--primary), var(--accent));
            width: 0%;
            transition: width 0.5s ease;
        }
        
        footer {
            text-align: center;
            padding: 25px;
            color: var(--gray);
            font-size: 1rem;
            border-top: 1px solid var(--light-gray);
            background: #f8fbff;
        }
        
        /* 滚动条样式 */
        .result-table-container::-webkit-scrollbar,
        .file-list::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }
        
        .result-table-container::-webkit-scrollbar-track,
        .file-list::-webkit-scrollbar-track {
            background: #f1f5ff;
            border-radius: 5px;
        }
        
        .result-table-container::-webkit-scrollbar-thumb,
        .file-list::-webkit-scrollbar-thumb {
            background: var(--primary);
            border-radius: 5px;
        }
        
        .result-table-container::-webkit-scrollbar-thumb:hover,
        .file-list::-webkit-scrollbar-thumb:hover {
            background: var(--primary-dark);
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease forwards;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        .highlight {
            background-color: #fff9c4 !important;
            transition: background-color 1s;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>MOWu台账Excel数据提取（测试版）</h1>
            <p class="subtitle">从供应链系统中导出Excel，提取指定数据并合并为新的excel（支持动态添加/删除需要提取的列，批量处理多个Excel文件）</p>
        </header>
        
        <div class="content">
            <div class="panel">
                <h2 class="panel-title">
                    <i class="fas fa-cog"></i> 配置与上传
                </h2>
                
                <div id="dropArea" class="drop-area">
                    <i class="fas fa-file-excel"></i>
                    <div class="drop-text">拖放Excel文件到此处</div>
                    <div class="drop-hint">支持多个Excel文件同时拖放</div>
                </div>
                
                <div class="columns-section">
                    <div class="columns-header">
                        <h3>需要提取的列：</h3>
                        <div id="columnsCount">4列</div>
                    </div>
                    
                    <div class="add-column-form">
                        <input type="text" id="newColumnInput" class="add-column-input" placeholder="输入新的列名...">
                        <button id="addColumnBtn" class="add-column-btn">
                            <i class="fas fa-plus"></i> 添加列
                        </button>
                    </div>
                    
                    <div class="columns-grid" id="columnsGrid">
                        <!-- 列将通过JS动态添加 -->
                    </div>
                </div>
                
                <div class="progress-container">
                    <div id="progressBar" class="progress-bar"></div>
                </div>
                
                <button id="processBtn" class="btn">
                    <i class="fas fa-play-circle"></i> 开始处理Excel文件
                </button>
                
                <div class="file-list">
                    <div class="file-list-header">
                        <h3>已上传文件</h3>
                        <div id="filesCount">0个文件</div>
                    </div>
                    <div id="fileList">
                        <div class="file-item">
                            <div class="file-name">尚未添加文件</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="panel">
                <h2 class="panel-title">
                    <i class="fas fa-table"></i> 提取结果
                </h2>
                
                <div class="result-title">
                    <h3>数据预览</h3>
                    <div id="rowCount">0行数据</div>
                </div>
                
                <div class="result-table-container">
                    <table class="result-table" id="previewTable">
                        <thead>
                            <tr id="tableHeaders">
                                <!-- 表头将通过JS动态生成 -->
                            </tr>
                        </thead>
                        <tbody id="previewBody">
                            <tr>
                                <td colspan="4" style="text-align: center; padding: 30px; color: var(--gray); font-style: italic;">
                                    <i class="fas fa-info-circle" style="font-size: 2rem; margin-bottom: 15px; display: block;"></i>
                                    处理Excel文件后，提取的数据将显示在这里
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <div class="status" id="statusArea">
                    <div class="status-icon info">
                        <i class="fas fa-info"></i>
                    </div>
                    <div id="statusText">等待处理文件...</div>
                </div>
                
                <button id="downloadBtn" class="btn download-btn hidden">
                    <i class="fas fa-download"></i> 下载合并的Excel文件
                </button>
            </div>
        </div>
        
        <footer>
            <p>供应链excel数据提取&copy; 2025 | 专为MoWu台账设计（支持动态列管理）</p>
        </footer>
    </div>

    <script>
        // 全局变量
        let uploadedFiles = [];
        let selectedColumns = ["品项名称", "单位", "数量", "生产时间"];
        const dropArea = document.getElementById('dropArea');
        const fileList = document.getElementById('fileList');
        const processBtn = document.getElementById('processBtn');
        const previewBody = document.getElementById('previewBody');
        const tableHeaders = document.getElementById('tableHeaders');
        const downloadBtn = document.getElementById('downloadBtn');
        const statusText = document.getElementById('statusText');
        const progressBar = document.getElementById('progressBar');
        const columnsGrid = document.getElementById('columnsGrid');
        const newColumnInput = document.getElementById('newColumnInput');
        const addColumnBtn = document.getElementById('addColumnBtn');
        const columnsCount = document.getElementById('columnsCount');
        const filesCount = document.getElementById('filesCount');
        const rowCount = document.getElementById('rowCount');
        
        // 合并后的数据
        let mergedData = [];
        
        // 初始化事件监听
        function init() {
            // 初始化列显示
            renderColumns();
            
            // 拖放事件
            dropArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropArea.classList.add('drag-over');
            });
            
            dropArea.addEventListener('dragleave', () => {
                dropArea.classList.remove('drag-over');
            });
            
            dropArea.addEventListener('drop', (e) => {
                e.preventDefault();
                dropArea.classList.remove('drag-over');
                
                const files = e.dataTransfer.files;
                handleFiles(files);
            });
            
            // 点击事件
            dropArea.addEventListener('click', () => {
                const input = document.createElement('input');
                input.type = 'file';
                input.multiple = true;
                input.accept = '.xlsx, .xls';
                
                input.onchange = (e) => {
                    handleFiles(e.target.files);
                };
                
                input.click();
            });
            
            // 处理按钮事件
            processBtn.addEventListener('click', processFiles);
            
            // 下载按钮事件
            downloadBtn.addEventListener('click', downloadMergedFile);
            
            // 添加列按钮
            addColumnBtn.addEventListener('click', addNewColumn);
            
            // 回车添加列
            newColumnInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    addNewColumn();
                }
            });
        }
        
        // 渲染列
        function renderColumns() {
            columnsGrid.innerHTML = '';
            
            if (selectedColumns.length === 0) {
                columnsGrid.innerHTML = '<div class="no-columns">请添加需要提取的列</div>';
                columnsCount.textContent = "0列";
                return;
            }
            
            selectedColumns.forEach((column, index) => {
                const columnItem = document.createElement('div');
                columnItem.className = 'column-item fade-in';
                columnItem.innerHTML = `
                    <div class="column-name">${column}</div>
                    <div class="column-remove" data-index="${index}">
                        <i class="fas fa-times"></i>
                    </div>
                `;
                
                columnsGrid.appendChild(columnItem);
            });
            
            // 添加删除事件
            document.querySelectorAll('.column-remove').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const index = parseInt(e.currentTarget.getAttribute('data-index'));
                    removeColumn(index);
                });
            });
            
            columnsCount.textContent = `${selectedColumns.length}列`;
        }
        
        // 添加新列
        function addNewColumn() {
            const newColumn = newColumnInput.value.trim();
            
            if (!newColumn) {
                showStatus('error', '请输入列名');
                highlightInput(newColumnInput);
                return;
            }
            
            if (selectedColumns.includes(newColumn)) {
                showStatus('error', `"${newColumn}" 列已存在`);
                highlightInput(newColumnInput);
                return;
            }
            
            selectedColumns.push(newColumn);
            newColumnInput.value = '';
            renderColumns();
            showStatus('success', `已添加列: ${newColumn}`);
        }
        
        // 高亮输入框
        function highlightInput(input) {
            input.style.borderColor = 'var(--danger)';
            input.style.boxShadow = '0 0 0 3px rgba(244, 67, 54, 0.2)';
            
            setTimeout(() => {
                input.style.borderColor = 'var(--primary-light)';
                input.style.boxShadow = 'none';
            }, 2000);
        }
        
        // 删除列
        function removeColumn(index) {
            const removedColumn = selectedColumns[index];
            selectedColumns.splice(index, 1);
            renderColumns();
            showStatus('info', `已移除列: ${removedColumn}`);
        }
        
        // 处理上传的文件
        function handleFiles(files) {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 检查文件类型
                if (!file.name.match(/\.(xlsx|xls)$/i)) {
                    showStatus('error', `"${file.name}" 不是Excel文件，已跳过`);
                    continue;
                }
                
                // 避免重复添加
                if (uploadedFiles.some(f => f.name === file.name && f.size === file.size)) {
                    continue;
                }
                
                uploadedFiles.push(file);
            }
            
            updateFileList();
            showStatus('success', `已添加 ${uploadedFiles.length} 个Excel文件`);
            filesCount.textContent = `${uploadedFiles.length}个文件`;
        }
        
        // 更新文件列表显示
        function updateFileList() {
            fileList.innerHTML = '';
            
            if (uploadedFiles.length === 0) {
                fileList.innerHTML = '<div class="file-item"><div class="file-name">尚未添加文件</div></div>';
                filesCount.textContent = "0个文件";
                return;
            }
            
            uploadedFiles.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                
                // 格式化文件大小
                const fileSize = formatFileSize(file.size);
                
                fileItem.innerHTML = `
                    <div class="file-name" title="${file.name}">${file.name}</div>
                    <div class="file-size">${fileSize}</div>
                    <div class="file-remove" data-index="${index}" title="移除文件">
                        <i class="fas fa-times"></i>
                    </div>
                `;
                
                fileList.appendChild(fileItem);
            });
            
            // 添加删除事件
            document.querySelectorAll('.file-remove').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const index = parseInt(e.currentTarget.getAttribute('data-index'));
                    uploadedFiles.splice(index, 1);
                    updateFileList();
                    showStatus('info', `已移除文件，剩余 ${uploadedFiles.length} 个文件`);
                    filesCount.textContent = `${uploadedFiles.length}个文件`;
                });
            });
            
            filesCount.textContent = `${uploadedFiles.length}个文件`;
        }
        
        // 处理文件
        async function processFiles() {
            if (uploadedFiles.length === 0) {
                showStatus('error', '请先添加Excel文件');
                return;
            }
            
            if (selectedColumns.length === 0) {
                showStatus('error', '请添加需要提取的列');
                return;
            }
            
            showStatus('info', `正在处理 ${uploadedFiles.length} 个文件...`);
            processBtn.disabled = true;
            downloadBtn.classList.add('hidden');
            
            // 重置预览
            previewBody.innerHTML = '';
            tableHeaders.innerHTML = '';
            mergedData = [];
            
            // 创建表头
            selectedColumns.forEach(col => {
                const th = document.createElement('th');
                th.textContent = col;
                tableHeaders.appendChild(th);
            });
            
            try {
                // 处理每个文件
                for (let i = 0; i < uploadedFiles.length; i++) {
                    const file = uploadedFiles[i];
                    const progress = ((i + 1) / uploadedFiles.length) * 100;
                    progressBar.style.width = `${progress}%`;
                    
                    const result = await processSingleFile(file);
                    
                    // 更新状态
                    showStatus('info', `处理中: ${file.name} (${i+1}/${uploadedFiles.length})`);
                    
                    // 合并数据
                    mergedData = [...mergedData, ...result.data];
                    
                    // 更新预览
                    if (i === uploadedFiles.length - 1) {
                        updatePreview(result.data);
                    }
                }
                
                showStatus('success', `处理完成！共提取 ${mergedData.length} 条数据`);
                downloadBtn.classList.remove('hidden');
                rowCount.textContent = `${mergedData.length}行数据`;
            } catch (error) {
                console.error('处理文件时出错:', error);
                showStatus('error', `处理文件时出错: ${error.message}`);
            } finally {
                processBtn.disabled = false;
                progressBar.style.width = '0%';
            }
        }
        
        // 处理单个文件
        function processSingleFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, {type: 'array'});
                        
                        // 获取第一个工作表
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        
                        // 转换为JSON
                        const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});
                        
                        if (jsonData.length === 0) {
                            reject(new Error(`${file.name} 是空文件`));
                            return;
                        }
                        
                        // 获取标题行
                        const headers = jsonData[0].map(h => h ? h.toString().trim() : '');
                        
                        // 创建列索引映射
                        const columnMap = {};
                        selectedColumns.forEach(col => {
                            const index = headers.indexOf(col);
                            columnMap[col] = index !== -1 ? index : null;
                        });
                        
                        // 检查是否有缺失的列
                        const missingColumns = selectedColumns.filter(col => columnMap[col] === null);
                        if (missingColumns.length > 0) {
                            showStatus('warning', `警告: 文件"${file.name}"中未找到列: ${missingColumns.join(', ')}`);
                        }
                        
                        // 提取数据
                        const extractedData = [];
                        for (let i = 1; i < jsonData.length; i++) {
                            const row = jsonData[i];
                            
                            // 跳过空行
                            if (!row || row.length === 0) continue;
                            
                            // 跳过"合计"行
                            if (row[0] && row[0].toString().includes('合计')) continue;
                            
                            const extractedRow = {};
                            
                            selectedColumns.forEach(col => {
                                const index = columnMap[col];
                                extractedRow[col] = index !== null && index < row.length ? row[index] : '';
                            });
                            
                            // 过滤掉没有数据的行
                            if (Object.values(extractedRow).some(val => val !== '')) {
                                extractedData.push(extractedRow);
                            }
                        }
                        
                        resolve({
                            fileName: file.name,
                            data: extractedData
                        });
                    } catch (error) {
                        reject(error);
                    }
                };
                
                reader.onerror = function() {
                    reject(new Error('读取文件失败'));
                };
                
                reader.readAsArrayBuffer(file);
            });
        }
        
        // 更新预览
        function updatePreview(data) {
            previewBody.innerHTML = '';
            
            if (data.length === 0) {
                const tr = document.createElement('tr');
                tr.innerHTML = `<td colspan="${selectedColumns.length}" style="text-align: center; padding: 30px; color: var(--gray);">
                    <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 15px; display: block;"></i>
                    没有提取到符合条件的数据
                </td>`;
                previewBody.appendChild(tr);
                return;
            }
            
            // 最多显示50行预览
            const previewRows = Math.min(data.length, 50);
            
            for (let i = 0; i < previewRows; i++) {
                const row = data[i];
                const tr = document.createElement('tr');
                tr.className = 'fade-in';
                
                selectedColumns.forEach(col => {
                    const td = document.createElement('td');
                    td.textContent = formatCellValue(row[col]);
                    tr.appendChild(td);
                });
                
                previewBody.appendChild(tr);
            }
            
            if (data.length > 50) {
                const tr = document.createElement('tr');
                tr.innerHTML = `<td colspan="${selectedColumns.length}" style="text-align: center; padding: 15px; color: var(--gray); font-style: italic;">
                    仅显示前50条记录，共 ${data.length} 条记录
                </td>`;
                previewBody.appendChild(tr);
            }
        }
        
        // 格式化单元格值
        function formatCellValue(value) {
            if (value === null || value === undefined) return '';
            
            // 处理日期
            if (value instanceof Date) {
                return value.toLocaleDateString();
            }
            
            // 处理数字
            if (typeof value === 'number') {
                // 如果是整数
                if (Number.isInteger(value)) {
                    return value.toString();
                }
                // 如果是小数
                return value.toFixed(4);
            }
            
            return value.toString();
        }
        
        // 下载合并后的文件
        function downloadMergedFile() {
            if (mergedData.length === 0) {
                showStatus('error', '没有数据可下载');
                return;
            }
            
            try {
                // 创建工作表
                const worksheet = XLSX.utils.json_to_sheet(mergedData);
                
                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '提取数据');
                
                // 生成Excel文件
                const date = new Date();
                const dateStr = `${date.getFullYear()}${(date.getMonth()+1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}`;
                XLSX.writeFile(workbook, `数据提取_${dateStr}.xlsx`);
                
                showStatus('success', '文件已开始下载');
            } catch (error) {
                console.error('生成Excel文件时出错:', error);
                showStatus('error', `生成文件失败: ${error.message}`);
            }
        }
        
        // 显示状态信息
        function showStatus(type, message) {
            statusText.textContent = message;
            
            // 清除所有状态类
            statusArea.className = 'status';
            
            // 添加当前状态类
            statusArea.classList.add(type);
            
            // 添加图标
            const icon = statusArea.querySelector('.status-icon');
            icon.innerHTML = '';
            
            switch(type) {
                case 'info':
                    icon.innerHTML = '<i class="fas fa-info"></i>';
                    break;
                case 'success':
                    icon.innerHTML = '<i class="fas fa-check"></i>';
                    break;
                case 'error':
                    icon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
                    break;
                case 'warning':
                    icon.innerHTML = '<i class="fas fa-exclamation-circle"></i>';
                    break;
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }
        
        // 初始化应用
        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>